<?php
namespace app\admin\controller;

use think\Db;

class Story extends Base
{
    public function config(){
        $list = Db::table('bze_config')
            ->where(['is_show'=>1,'location'=>4])
            ->order('sort')
            ->select();
        return $this->fetch('', [
            'list'  =>  $list,
            'list2'  =>  json_encode($list),
        ]);
        return $this->fetch();
    }

    public function index() {
        return $this->fetch();
    }

    public function itemList(){
        $list = model('StoryItem')->order(['type'=>'DESC', 'sort'=>'ASC'])->select();
        return $this->fetch('', [
            'list' => $list,
        ]);
    }

    public function addStoryItem(){
        if(!request()->isPost()){
            $typeList = model('StoryItem')->getTypeArr();
            return $this->fetch('', [
                'typeList' => $typeList,
            ]);
        }else{
            $postData = input('post.');
            $type = $postData['type'];
            switch ($type){
                case '0':
                    $postData['content'] = $postData['content0'];
                    break;
                case '1':
                    $postData['content'] = $postData['content1'];
                    break;
                case '2':
                    $postData['content'] = $postData['content2'];
                    break;
            }
            $res = model('StoryItem')
                ->add($postData);
            if(false!==$res){
                return show(0, '添加成功');
            }else{
                return show(0, '添加失败');
            }
        }
    }

    public function editStoryItem(){
        $id = input('param.id');
        if(!request()->isPost()){
            $this->initEditor();
            $item = model('StoryItem')->find($id);
            $type = $item->getData('type');
            $item = $item->toArray();
            $item['type'] = $type;
            return $this->fetch('', [
                'item' => $item,
            ]);
        }
        $res = model('StoryItem')
            ->save(input('post.'),['id'=>$id]);
        if(false!==$res){
            return show(0, '更新成功');
        }else{
            return show(0, '更新失败');
        }
    }

    /**
     * @description :[删除]
     * @return array
     */
    public function deleteStoryItem(){
        $postData = input('post.');
        $id = $postData['id'];
        $res = model('StoryItem')->where(['id'=>$id])->delete();
        if(false !== $res){
            return show(0, '删除成功');
        }else{
            return show(1, '删除成功');
        }
    }

    /**
     * 初始化编辑器链接
     * 本编辑器参考 地址 http://fex.baidu.com/ueditor/
     */
    function initEditor(){
        $server_url = "/Admin/Ueditor/index";
        $this->assign('server_url', $server_url);
    }

}
